" vim: set sts=2 sw=2
" vim:fdm=marker
"
" Outputz for vim plugin
"
" Maintainer:  gtaka555
" Last Modify: 2009-04-02
" Since:       2008-11-22
" Version:     0.0.4
"

if !has('ruby')
  finish
endif

if exists("b:outputz_plugin")
  finish
endif
let b:outputz_plugin = 1

" valuables : {{{1
let g:outputz_version = '0.0.4'

if !exists('g:outputz_key')
  finish
endif

if !exists('g:outputz_uri')
  " Not Use
  let g:outputz_uri = 'http://localhost/vim/'
endif

if !exists('g:outputz_default_ftype')
  let g:outputz_default_ftype = 'text'
endif

if !exists('g:outputz_user_agent')
  " Not Use
  let g:outputz_user_agent = 'vim-outputz/' . g:outputz_version
endif

if !exists('g:outputz_save_file')
  " Not Use
  let g:outputz_save_file = ''
endif

if !exists('g:outputz_post_uri')
  let g:outputz_post_uri = 'http://outputz.com/api/post'
endif

" }}}

" autocommands : {{{1
au BufNewFile,BufReadPost * :call <SID>Initialize()
au BufWritePost * :call <SID>Update()
" }}}

" commands : {{{1
command! OutputzWc call <SID>CountChar()
command! OutputzModeOn call <SID>ModeSwitch(1)
command! OutputzModeOff call <SID>ModeSwitch(0)
" }}}

" functions : {{{1
func! s:Initialize()
  let b:outputz_file_size = s:CountChar()
  let b:outputz_active = 1
endfun

func! s:Update()
  let s:new_file_size = s:CountChar()

  if s:new_file_size > b:outputz_file_size && b:outputz_active == 1
    call s:Send(s:new_file_size - b:outputz_file_size)
  endif

  let b:outputz_file_size = s:new_file_size

" echo "Count: " . b:outputz_file_size
endfun

func! s:Send(size)
  if &ft == ''
    let s:uri = 'vim://' . g:outputz_default_ftype . '/'
  else
    let s:uri = 'vim://' . &ft . '/'
  endif

  " TODO: URL encoded parameters
  " TODO: use User-Agent

  let s:cmd = 'curl -si -d key=' . g:outputz_key
  let s:cmd = s:cmd . ' -d uri="' . s:uri . '" -d size=' . a:size
  let s:cmd = s:cmd . ' ' . g:outputz_post_uri

  let s:res = system(s:cmd)
" echo ">> [" . s:res . "]"

  " TODO: check HTTP status

  return
endfun

fun! s:CountChar()
  let s:total = 0

  let s:total = getfsize(expand('%:p'))

  return s:total
endfun

fun! s:ModeSwitch(flag)

  if a:flag == 0
    let b:outputz_active = 0
  elseif a:flag == 1
    let b:outputz_active = 1
  end

  return
endfun
" }}}

